package me.hgj.jetpackmvvm.ledun.ui.activity

import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.WindowManager
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.Navigation
import cn.com.heaton.blelibrary.ble.Ble
import cn.com.heaton.blelibrary.ble.BleLog
import cn.com.heaton.blelibrary.ble.callback.BleScanCallback
import cn.com.heaton.blelibrary.ble.model.BleDevice
import cn.com.heaton.blelibrary.ble.utils.UuidUtils
import com.blankj.utilcode.util.ToastUtils
import com.i502tech.appkotlin.MyBleWrapperCallback
import me.hgj.jetpackmvvm.ledun.R
import me.hgj.jetpackmvvm.ledun.app.appViewModel
import me.hgj.jetpackmvvm.ledun.app.base.BaseActivity1
import me.hgj.jetpackmvvm.ledun.app.util.StatusBarUtil
import me.hgj.jetpackmvvm.ledun.databinding.ActivityMainBinding
import me.hgj.jetpackmvvm.ledun.viewmodel.state.MainViewModel
import me.hgj.jetpackmvvm.network.manager.NetState
import java.util.UUID

/**
 * 项目主页Activity
 */
class MainActivity : BaseActivity1<MainViewModel, ActivityMainBinding>() {
    companion object{
        private const val REQUEST_CODE: Int = 0x01
    }
    var exitTime = 0L
    private lateinit var mBle: Ble<BleDevice>
    private var listDatas = mutableListOf<BleDevice>()

    lateinit var viewModel: MainViewModel
    override fun initView(savedInstanceState: Bundle?) {
//        Ble.options()
//            .setUuidService(替换成自己的service_uuid)必选
//                .setUuidWriteCha(替换成自己的write_uuid)写入必选
//                .setUuidReadCha(替换成自己的read_uuid)读取必选


        //进入首页检查更新
//        Beta.checkUpgrade(false, true)
//        viewModel.shareIsConnect.value=false
        viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
        onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                val nav = Navigation.findNavController(this@MainActivity, R.id.host_fragment)
                if (nav.currentDestination != null && nav.currentDestination!!.id != R.id.mainfragment) {
                    //如果当前界面不是主页，那么直接调用返回即可
                    nav.navigateUp()
                } else {
                    //是主页
                    if (System.currentTimeMillis() - exitTime > 2000) {
                        ToastUtils.showShort("再按一次退出程序")
                        exitTime = System.currentTimeMillis()
                    } else {
                        finish()
                    }
                }
            }
            })
        appViewModel.appColor.value?.let {
            window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
            supportActionBar?.setBackgroundDrawable(ColorDrawable(it))
            StatusBarUtil.setColor(this, it, 0) }


        requestBLEPermission()

    }


    private fun requestBLEPermission() {
        ActivityCompat.requestPermissions(this, arrayOf(
            Manifest.permission.BLUETOOTH_ADMIN,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_BACKGROUND_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION), REQUEST_CODE)
    }


    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_CODE) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    // 判断用户是否 点击了不再提醒。(检测该权限是否还可以申请)
                    val b = shouldShowRequestPermissionRationale(permissions[0])
                    if (!b) {
                        // 用户还是想用我的 APP 的
                        // 提示用户去应用设置界面手动开启权限
                    } else
                        finish()
                } else {
                    Log.e("laiyiwen", "onRequestPermissionsResult: 申请权限成功111" )
                    initBLE()

                }
            }
        }

    }
    //初始化蓝牙
    private fun initBLE() {
        mBle = Ble.options().apply {
            logBleEnable = true
            throwBleException = true
            autoConnect = true
            connectFailedRetryCount = 3
            connectTimeout = 10000L
            scanPeriod = 12000L
            uuidService = UUID.fromString(UuidUtils.uuid16To128("fd00"))
            uuidWriteCha = UUID.fromString(UuidUtils.uuid16To128("fd01"))
            bleWrapperCallback = MyBleWrapperCallback()
            /*factory = object : BleFactory<MyDevice>() {
                //实现自定义BleDevice时必须设置
                override fun create(address: String, name: String): MyDevice{
                    return MyDevice(address, name) //自定义BleDevice的子类
                }
            }*/
        }.create(applicationContext, object : Ble.InitCallback{
            override fun failed(failedCode: Int) {
                BleLog.i("laiyiwen", "init failed: $failedCode")
            }

            override fun success() {
                BleLog.i("laiyiwen", "init success")
            }

        })
        //3、检查蓝牙是否支持及打开
        checkBluetoothStatus()
    }

    //检查蓝牙是否支持及打开
    private fun checkBluetoothStatus() {
        // 检查设备是否支持BLE4.0
        if (!mBle.isSupportBle(this)) {
            ToastUtils.showLong("该设备不支持BLE蓝牙")
            finish()
        }
        if (!mBle.isBleEnable) {
            //4、若未打开，则请求打开蓝牙
            val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            if (ActivityCompat.checkSelfPermission(
                    this,
                    Manifest.permission.BLUETOOTH_ADMIN
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return
            }
            startActivityForResult(enableBtIntent, Ble.REQUEST_ENABLE_BT)
        } else {
            //5、若已打开，则进行扫描
            mBle.startScan(bleScanCallback())
        }
    }

    private fun bleScanCallback(): BleScanCallback<BleDevice> {
        return object : BleScanCallback<BleDevice>() {
            override fun onLeScan(device: BleDevice?, rssi: Int, scanRecord: ByteArray?) {
                if (TextUtils.isEmpty(device?.bleName)){
                    return
                }
                for (d in listDatas) {
                    if (d.bleAddress == device?.bleAddress){
                        return
                    }
                }
                device?.let {
                    listDatas.add(it)
                    viewModel.addDevice(it)
                    Log.e("laiyiwen", "onLeScan: ========================================" )
                    listDatas.forEach {
                        Log.e("laiyiwen", "onLeScan: +${it.bleName}" )
                    }
//                    adapter.notifyDataSetChanged()
                }

            }
        }
    }




    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                val i = ContextCompat.checkSelfPermission (this, Manifest.permission.ACCESS_COARSE_LOCATION)
                if (i != PackageManager.PERMISSION_GRANTED) {
                    // 提示用户应该去应用设置界面手动开启权限
                } else {
                    //权限申请成功
                    Log.e("laiyiwen", "onRequestPermissionsResult: 申请权限成功" )

                    initBLE()
                }
            }
        }
    }
//



    override fun createObserver() {
        appViewModel.appColor.observeInActivity(this, Observer {
            supportActionBar?.setBackgroundDrawable(ColorDrawable(it))
            StatusBarUtil.setColor(this, it, 0)
        })
    }

    /**
     * 示例，在Activity/Fragment中如果想监听网络变化，可重写onNetworkStateChanged该方法
     */
    override fun onNetworkStateChanged(netState: NetState) {
        super.onNetworkStateChanged(netState)
        if (netState.isSuccess) {
            Toast.makeText(applicationContext, "我特么终于有网了啊!", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(applicationContext, "我特么怎么断网了!", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mBle.released()
    }

}
